package com.api.gc;


import cn.hutool.core.lang.UUID;
import com.api.gc.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import weaver.admincenter.file.FileUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: tyc
 * @Date: 2024/3/26 14:40
 * @Description:
 **/
@Path("/downloadTemplete")
public class DownloadFile {
    @Path("/download")
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)//返回方式为流
    public String downloadModel(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        String fileName = request.getParameter("fileName");
        String id = request.getParameter("id");
        try {
                String filePath = "";
                setAttachmentResponseHeader(request,response, fileName);
                File file = new File("/data/unstructured/template/"+id+".xls");
                if (file.exists()){
                    filePath = "/data/unstructured/template/"+id+".xls";
                }else {
                    file = new File("/data/unstructured/template/"+id+".xlsx");
                    if (file.exists()){
                        filePath = "/data/unstructured/template/"+id+".xlsx";
                    }else{
                        file = new File("/data/unstructured/template/"+id);
                        if (file.exists()){
                            filePath = "/data/unstructured/template/"+id;
                        }
                    }
                }
                if (StringUtils.isBlank(filePath)){
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found.");
                    return "File not found";
                }
                writeBytes(filePath, response.getOutputStream());
                response.flushBuffer();
        } catch (Exception e) {
            // 处理异常，例如网络错误、IO错误等
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to download the file.");
        }
        return "";
    }

    @Path("/downloadOCR")
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)//返回方式为流
    public String downloadOCR(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        String fileName = request.getParameter("fileid");
        try {
            String filePath = "";
            setAttachmentResponseHeader(request,response, fileName);
            File file = new File("/data/unstructured/DZDA/cover/"+fileName);
            if (file.exists()){
                filePath = file.getAbsolutePath();
            }else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to download the file.");
                return "";
            }
            if (StringUtils.isBlank(filePath)){
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found.");
                return "File not found";
            }
            writeBytes(filePath, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            // 处理异常，例如网络错误、IO错误等
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to download the file.");
        }
        return "";
    }

    @Path("/genarateModel")
    @POST
    @Produces(MediaType.APPLICATION_JSON)//返回方式为JSON
    public Result genarateModel(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        String titles = request.getParameter("titles");
        try {
                //生成临时模板
                String tempFileName = UUID.fastUUID()+".xls";
                File newFile = new File("/data/unstructured/template/tempFile/"+tempFileName);
                newFile.createNewFile();
                File init = new File("/data/unstructured/template/tempFile/INIT.xls");
                FileUtil.copyFile(init, newFile);
                List<String> titleList = Arrays.asList(titles.split(","));
                FileInputStream fis = new FileInputStream(newFile);
                Workbook workbook = new HSSFWorkbook(fis);
                Sheet sheet = workbook.getSheetAt(0);
                Row newRow = sheet.createRow(0);
                for (int j = 0; j < titleList.size(); j++) {
                    String key = titleList.get(j);
                    Cell cell = newRow.createCell(j);
                    key = key.replaceAll("[\\s\\u00A0]+","").trim();
                    cell.setCellValue(key);
                    //创建单元格样式
                    CellStyle style = workbook.createCellStyle();
                    style.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("@"));
                    cell.setCellStyle(style);
                }
                // 保存更改到新文件
                try (FileOutputStream fos = new FileOutputStream(newFile)) {
                    workbook.write(fos);
                }finally {
                    workbook.close();
                    fis.close();
                }
                return Result.ok(tempFileName);
        } catch (Exception e) {
            // 处理异常，例如网络错误、IO错误等
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 下载默认模板
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @Path("/downloadDefaultModel")
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)//返回方式为流
    public String downloadDefaultModel(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        String fileName = request.getParameter("fileName");
        String realFileName = request.getParameter("realFileName");
        String filePath = "/data/unstructured/template/tempFile/"+realFileName;
        String agent = request.getHeader("User-Agent");
        if (agent.contains("MSIE")||agent.contains("Trident"))
        {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }
        else
        {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "UTF-8") + "\"");
            fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        }
        String extension = "";
        int i = realFileName.lastIndexOf('.');
        if (i > 0) {
            extension = realFileName.substring(i+1); // 获取后缀名
        }
        if (extension.equals("xls")){
            response.setContentType("application/vnd.ms-excel; charset=UTF-8");
        }else if (extension.equals("xlsx")){
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setHeader("download-filename", fileName);
        if (StringUtils.isBlank(filePath)){
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found.");
            return filePath;
        }
        writeBytes(filePath, response.getOutputStream());
        response.flushBuffer();
        if (new File(filePath).exists()){
            new File(filePath).delete();
        }
        return filePath;
    }

    @Path("/downloadExcel")
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)//返回方式为流
    public String downloadExcel(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        String fileName = request.getParameter("fileName");
        fileName = "数据导出-"+ LocalDateTime.now().toString().replace("T"," ").replace(":","-")+"-" +fileName;
        String readFileName = request.getParameter("readFileName");
        String filePath = "/data/unstructured/template/tempFile/"+readFileName;
        String agent = request.getHeader("User-Agent");
        if (agent.contains("MSIE")||agent.contains("Trident"))
        {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }
        else
        {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "UTF-8") + "\"");
            fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        }
        String extension = "";
        int i = readFileName.lastIndexOf('.');
        if (i > 0) {
            extension = readFileName.substring(i+1); // 获取后缀名
        }
        if (extension.equals("xls")){
            response.setContentType("application/vnd.ms-excel; charset=UTF-8");
        }else if (extension.equals("xlsx")){
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setHeader("download-filename", fileName);
        if (StringUtils.isBlank(filePath)){
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found.");
            return filePath;
        }
        writeBytes(filePath, response.getOutputStream());
        response.flushBuffer();
        if (new File(filePath).exists()){
            new File(filePath).delete();
        }
        return filePath;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response 响应对象
     * @param realFileName 真实文件名
     */
    public static void setAttachmentResponseHeader(HttpServletRequest request,HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
    {
        String agent = request.getHeader("User-Agent");
        if (agent.contains("MSIE")||agent.contains("Trident"))
        {
            realFileName = URLEncoder.encode(realFileName, "UTF-8");
        }
        else
        {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(realFileName.getBytes("UTF-8"), "UTF-8") + "\"");
            realFileName = new String(realFileName.getBytes("UTF-8"),"ISO-8859-1");
        }
        response.setContentType("application/pdf;chartset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + realFileName + "\"");
        //response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        //response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", realFileName);
    }
    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        File file = new File(filePath);
        System.out.println("==============文件大小===============>>>"+file.length());
        try(FileInputStream fis = new FileInputStream(file) )
        {

            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }finally {
            if (os!=null){
                os.close();
            }
        }
    }


    public static void writeBytes(File file, OutputStream os) throws IOException
    {
        System.out.println("==============文件大小===============>>>"+file.length());
        try(FileInputStream fis = new FileInputStream(file) )
        {

            if (!file.exists())
            {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }finally {
            if (os!=null){
                os.close();
            }
        }
    }

    /**
     * 解密
     *
     * @param sSrc
     * @param sKey
     * @return
     */
    public static String decrypt(String sSrc, String sKey) {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted = parseHexStr2Byte(sSrc);//先用base64解密

            byte[] original = cipher.doFinal(encrypted);
            String originalString = new String(original, "utf-8");
            return originalString;

        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
